#!/usr/bin/env gosh

(use sxml.ssax)
(use sxml.sxpath)
(use sxml.tools)
(use sxml.serializer)
(use text.html-lite)
(use text.tree)
(use www.cgi)
(use gauche.charconv)
(use gauche.process)

(define (cgi-on-error-proc e)
  `(html
    (head (title "Error"))
    (body (h1 "Error")
	  (p ,(html-escape-string (slot-ref e 'message))))))

(define (cgi-output-proc tree)
  (define (writer tree)
    (display "Content-type: text/xml\r\n\r\n")
    (display "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
    (srl:sxml->xml tree (current-output-port)))

  (if (ces-equivalent? (gauche-character-encoding)
                       (cgi-output-character-encoding))
    (writer tree)
    ;; NB: we avoid using wrap-with-output-conversion, for we want
    ;; to make sure output is flushed each time in case cgi-main
    ;; is used in a persistent process.
    (with-output-conversion
     (current-output-port)
     (cut writer tree)
     :encoding (cgi-output-character-encoding))))

(define (main args)
  (cgi-main
    (lambda (params)
      `(html
	(head (title "Example"))
	(body
	 (table
	  (tr (th "Name") (th "Value"))
	  ,@(map (lambda (p)
		   `(tr
		     (td ,(html-escape-string (car p)))
		     (td ,(html-escape-string (x->string (cdr p))))))
		 params)
	  (div
	   ,@((sxpath "//cat")
	      ;;"/home/teruaki/garakuta-okiba/wnix/cat.scm -n=//item /home/teruaki/garakuta-okiba/mp3tunes_fuse/root/track_playlist/Newest\\ tracks/*.xml"
	      ;;(cgi-get-parameter "q" params)))
	      (call-with-input-process
		  "/home/teruaki/garakuta-okiba/wnix/cat.scm -n=//item /home/teruaki/garakuta-okiba/mp3tunes_fuse/root/track_playlist/Newest\\ tracks/*.xml | /home/teruaki/garakuta-okiba/wnix/cmd.scm -n=//item -k=\"//albumTitle/text()\" -c=\"sort\" | /home/teruaki/garakuta-okiba/wnix/tr.scm -n=//item/albumTitle -c=\"tr [:lower:] [:upper:]\""
		(cut ssax:xml->sxml <> '()))))))))
    :on-error    cgi-on-error-proc
    :output-proc cgi-output-proc))

;; Local variables:
;; mode: inferior-gauche
;; end:
